# calibration_dialog.py
from PyQt5.QtWidgets import (
    QDialog,
    QVBoxLayout,
    QHBoxLayout,
    QPushButton,
    QGraphicsView,
    QMessageBox,
)
from ui.calibration_scene import CalibrationScene
from PyQt5.QtGui import QPainter


class CalibrationDialog(QDialog):
    def __init__(self, image_path, parent=None):
        super().__init__(parent)
        self.setWindowTitle("手动标定天牛位置")
        self.resize(800, 600)

        self.setStyleSheet(
            """
            QDialog {
                background-color: #e0f8e0;
            }
            QPushButton {
                font-size: 16px;
                padding: 6px;
                border-radius: 10px;
                background-color: #c0e4c0;
            }
            QPushButton:hover {
                background-color: #a8d4a8;
            }
        """
        )

        self.image_path = image_path
        self.boxes = []

        layout = QVBoxLayout(self)

        btn_layout = QHBoxLayout()

        self.btn_save = QPushButton("保存标定")
        self.btn_save.clicked.connect(self.accept)

        self.btn_clear = QPushButton("清除标记")
        self.btn_clear.clicked.connect(self.clear_marks)

        self.btn_zoom_in = QPushButton("放大")
        self.btn_zoom_in.clicked.connect(self.zoom_in)

        self.btn_zoom_out = QPushButton("缩小")
        self.btn_zoom_out.clicked.connect(self.zoom_out)

        btn_layout.addWidget(self.btn_save)
        btn_layout.addWidget(self.btn_clear)
        btn_layout.addWidget(self.btn_zoom_in)
        btn_layout.addWidget(self.btn_zoom_out)

        self.scene = CalibrationScene(self)
        self.scene.set_image(image_path)

        self.view = QGraphicsView(self.scene)
        self.view.setRenderHint(QPainter.Antialiasing)
        self.view.setDragMode(QGraphicsView.RubberBandDrag)

        layout.addLayout(btn_layout)
        layout.addWidget(self.view)

    def clear_marks(self):
        self.scene.clear_all()

    def zoom_in(self):
        self.view.scale(1.2, 1.2)

    def zoom_out(self):
        self.view.scale(0.8, 0.8)

    def accept(self):
        self.boxes = self.scene.get_normalized_boxes()
        super().accept()
